package com.neuedu.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.boot.entity.User;
import com.neuedu.boot.framework.Res;
import com.neuedu.boot.service.IUserService;
import com.neuedu.boot.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目：      springboot
 * 类名:       LoginController
 * 创建时间：  2024/4/3 09：37
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@RestController
public class LoginController {

    @Autowired
    IUserService userService;


    /**
     * http://localhost:8080/login
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public Res login(@RequestBody User user ){
        // 1 验证用户名、密码是否正确
        Res result = null;
       User queryUser = getUserByPassword(user.getUsername(),user.getPassword());
        if(queryUser != null){
            String token = JWTUtils.encode(queryUser);
            result = Res.ok(token);
        }else{
            result = Res.failed(401,"用户名或者密码错误");
        }

        return  result;
    }


    /**
     * 根据用户名密码获取登录对象
     * @param username
     * @param password
     * @return
     */
    private  User getUserByPassword(String username,String password){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        return userService.getOne(queryWrapper);
    }


}
